package review.system.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import review.dao.RoleDAO;
import review.dao.UserRoleDAO;
import review.entity.Roles;
import review.entity.UserRole;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

  @Autowired
  private RoleDAO roleDAO;

  @Autowired
  private UserRoleDAO userRoleDAO;

  // 添加角色
  public void addRoles(Roles roles) {
    if (roles.getName() == null) {
      throw new RuntimeException("未添加角色名");
    }
    if (roleDAO.findByName(roles.getName()) != null) {
      throw new RuntimeException("该角色已存在");
    }
    roleDAO.save(roles);
  }

  // 判断名称或ID
  public Roles roleJudge(Roles roles) {
    if (roles.getId() == null) {
      if (roles.getName() == null) {
        throw new RuntimeException("用户名或ID为空");
      } else {
        Roles r = roleDAO.findByName(roles.getName());
        if (r == null) {
          throw new RuntimeException("该角色不存在");
        }
        return r;
      }
    } else {
      Optional<Roles> rolesOptional = roleDAO.findById(roles.getId());
      if (!rolesOptional.isPresent()) {
        throw new RuntimeException("ID不存在");
      }
      return rolesOptional.get();
    }
  }

  // 修改角色
  public void updateRoles(Roles roles) {

    Roles r = roleJudge(roles);
    r.setName(roles.getName());
    roleDAO.save(r);
  }

  // 删除角色
  public void deleteRoles(Roles roles) {
    Roles r = roleJudge(roles);
    List<UserRole> userRoles = userRoleDAO.findByRoleid(r.getId());
    if (!userRoles.isEmpty()) {
      throw new RuntimeException("角色已经被绑定");
    }
    roleDAO.delete(r);
  }

  // 查询全部角色
  public List<Roles> findAllRoles() {
    List<Roles> list = roleDAO.findAll(Sort.by(Sort.Direction.ASC, "id"));
    return list;
  }

}
